package com.jokerpan.project.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jokerpan.project.commons.PaginationBuilder;
import com.jokerpan.project.entity.Flows;
import com.jokerpan.project.entity.UserAction;
import com.jokerpan.project.mapper.FlowsMapper;
import com.jokerpan.project.mapper.UserActionMapper;
import com.jokerpan.project.service.UserActionService;
import com.jokerpan.project.util.UserTool;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jokerpan
 */
@Service("userActionService")
public class UserActionServiceImpl implements UserActionService {

    @Resource
    UserActionMapper userActionMapper;
    @Resource
    FlowsMapper flowsMapper;
    @Resource
    UserTool userTool;

    @Override
    public Map<String, Object> queryList(UserAction userAction) {
        Page<Object> page = PageHelper.startPage(userAction.getCurrentPage(), userAction.getPageSize());
        List<UserAction> resultList = this.userActionMapper.queryList(userAction);
        return PaginationBuilder.buildResult(resultList, page.getTotal(), userAction.getCurrentPage(), userAction.getPageSize());
    }

    @Override
    public Map<String, Object> queryChartData(UserAction userAction) {
        Map<String, Object> map = new LinkedHashMap<>();
        List<UserAction> fans = this.userActionMapper.queryFans(userAction);
        List<UserAction> views = this.userActionMapper.queryViews(userAction);
        map.put("fans", fans);
        map.put("views", views);
        return map;
    }

    @Override
    public boolean add(UserAction userAction) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String actionType = userAction.getActionType();
        if (actionType.equals("follow")){
            Flows flows = new Flows();
            flows.setUserId(userAction.getUserId());
            flows.setFlowUserId(userAction.getObjId());
            flows.setFlowTime(format.format(new Date()));
            flowsMapper.add(flows);
            userTool.refreshRedis();
        }
        userAction.setActionTime(format.format(new Date()));
        userAction.setContent("");
        userAction.setVisible(1);
        return userActionMapper.add(userAction) > 0;
    }

    @Override
    public boolean deleteById(Integer id) {
        return userActionMapper.deleteById(id) > 0;
    }

    @Override
    public boolean cancelFollow(Integer userId, Integer flowUserId) {
        boolean flag = flowsMapper.cancelFollow(userId, flowUserId) > 0;
        userTool.refreshRedis();
        return flag;
    }
}
